import numpy as np
import cv2
from PIL import Image

def compute_mae(pred, gt):
    if pred.shape != gt.shape:
        gt = np.array(Image.fromarray(gt).resize(pred.shape[::-1], Image.BILINEAR))
    return np.mean(np.abs(pred - gt))


def compute_f_measure(pred, gt):
    # Resize gt to match pred shape if needed
    if pred.shape != gt.shape:
        gt = np.array(Image.fromarray(gt).resize(pred.shape[::-1], Image.BILINEAR))

    pred = pred / 255.0 if pred.max() > 1 else pred
    gt = gt / 255.0 if gt.max() > 1 else gt

    binary = (pred >= 0.5).astype(np.uint8)
    gt = (gt >= 0.5).astype(np.uint8)

    tp = np.sum(binary * gt)
    precision = tp / (np.sum(binary) + 1e-6)
    recall = tp / (np.sum(gt) + 1e-6)

    f = 2 * precision * recall / (precision + recall + 1e-6)
    return f

def evaluate_dataset(pred_list, gt_list):
    """
    pred_list and gt_list: list of file paths to predicted maps and GT masks
    """
    mae_total, f_total = 0.0, 0.0
    for pred_path, gt_path in zip(pred_list, gt_list):
        pred = cv2.imread(pred_path, cv2.IMREAD_GRAYSCALE)
        gt = cv2.imread(gt_path, cv2.IMREAD_GRAYSCALE)
        mae_total += compute_mae(pred, gt)
        f_total += compute_f_measure(pred, gt)
    num = len(pred_list)
    return f_total / num, mae_total / num
